var pomelo = require('pomelo');
var logger = require('pomelo-logger').getLogger('pomelo');

require('./app/util/global');

var routeUtil = require('./app/util/routeUtil');
var world = require('./app/logic/world/world');
var hall = require('./app/logic/hall/hall');
var cache = require('./app/logic/cache/cache');
var game = require('./app/logic/game/game');

var gameRoomFilter = require('./app/servers/game/filter/roomFilter');
var hallLoggerFilter = require('./app/servers/hall/filter/loggerFilter');
var worldLoggerFilter = require('./app/servers/world/filter/loggerFilter');

/**
 * Init app for client.
 */
var app = pomelo.createApp();
app.set('name', 'BCE');

// app configuration
app.configure('production|development', 'connector', function(){
	app.set('connectorConfig',
		{
			connector : pomelo.connectors.hybridconnector,
			heartbeat : 15,
		});
});

app.configure('production|development', 'gate', function(){
	app.set('connectorConfig',
		{
			connector : pomelo.connectors.hybridconnector,
			useProtobuf : true
		});
});

app.configure('production|development', 'world', function () {
	world.init();
	app.filter(worldLoggerFilter());

    app.beforeStopHook(function() {
        world.stop();
    });
});

app.configure('production|development', 'hall', function () {
	hall.init();
	app.filter(hallLoggerFilter());

	app.beforeStopHook(function() {
		hall.stop();
	});
});

app.configure('production|development', 'cache', function () {
	cache.init();

	app.beforeStopHook(function() {
		cache.stop();
	});
});

app.configure('production|development', 'game', function () {
    app.filter(gameRoomFilter());
    game.init();

	app.beforeStopHook(function() {
		game.stop();
	});
});

// app configure
app.configure('production|development', function() {

	if (app.serverType !== 'master') {
		var servers = app.get('servers').game;
		var gameServers = [];
		var sceneServers = [];
		var matchServers = [];
		servers.forEach(function(server) {
			if (server.scene) {
				sceneServers.push(server);
			} else if (server.match) {
				matchServers.push(server);
			} else {
				gameServers.push(server);
			}
		});

		app.set('gameServers', gameServers);
		app.set('sceneServers', sceneServers);
		app.set('matchServers', matchServers);
	}

    // route configures
    app.route('game', routeUtil.game);

    // filter configures
    app.filter(pomelo.timeout());
});


// start app
app.start();

process.on('uncaughtException', function(err) {
	logger.error("Caught exception: %j", err.stack);
});
